package cn.chendd;

import de.codecentric.boot.admin.server.config.AdminServerProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;

/**
 * Spring Boot Admin 安全验证
 *
 * @author chendd
 * @date 2022/10/18 17:03
 */
@Configuration
public class SecurityPermitAllConfig extends WebSecurityConfigurerAdapter {

    private final AdminServerProperties serverProperties;

    public SecurityPermitAllConfig(@Autowired AdminServerProperties serverProperties) {
        this.serverProperties = serverProperties;
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        ///所有地址不需要权限访问，即不需要登录和登出
        /*httpSecurity.authorizeRequests().anyRequest().permitAll();*/
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setTargetUrlParameter("redirectTo");
        successHandler.setDefaultTargetUrl(serverProperties.path("/"));

        httpSecurity.authorizeRequests()
                //配置所有的静态资源和登录地址运行免登陆访问
                .antMatchers(serverProperties.path("/assets/**")).permitAll()
                .antMatchers(serverProperties.path("/login")).permitAll()
                .antMatchers(serverProperties.path("/instances/**")).permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage(serverProperties.path("/login")).successHandler(successHandler)
                .and().logout().logoutUrl(serverProperties.path("/logout"))
                .and().httpBasic().and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                .ignoringAntMatchers(
                        serverProperties.path("/instances"),
                        serverProperties.path("/actuator/**")
                );
    }

}
